$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("PcmM4")
    const dgrid1 = $NG.getCmpApi("PcmD4")
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    const user = $NG.getUser()
    const listForm = $NG.getCmpApi("CntList")

    hiddenDetail(['AdvancePayment','DeductionReward','ContractTerms'])
    setRequiredLx()
    


    try {
        const param = parseUrlParams(location.href)
        console.log(`param`, param);
        listForm.getItem("PhidSupplyEnt*int64*eq*1").setValue({
            label: param.gys_name,
            value: param.gys_phid
        })
        if (listForm) {
        setTimeout(()=>{
            listForm.query()
        },300)

        }
    } catch (err) {
        console.log("非列表无视，错误：", err)
    }

    // if(!mstform.getItem("user_fbfmc").getValue()){
    //     mstform.getItem("user_fbfmc").setValue({
    //         label:user.orgName,
    //         value:user.orgID
    //     })
    // }

    useValuesChange(() => {
        getProjectInfoByPhid()
    }, "user_lxsqbh")

    useValuesChange(() => {
        getSupplyInfo()
    }, "PhidSupplyEnt")
    
      useValuesChange(() => {
       setRequiredLx()
    }, "user_htesfdysswy")

    useValuesChange(()=>{
      const rows = dgrid1.getRows()
    rows.forEach(el=>{
      el.TaxRate = mstform.getItem("user_sl").getValue()
    })
    dgrid1.refreshView()
    },"user_sl")
  useUpdateRows(()=>{
    const rows = dgrid1.getRows()
    rows.forEach(el=>{
      el.TaxRate = mstform.getItem("user_sl").getValue()
    })
    dgrid1.refreshView()
  },"ContractList")
  
  function setRequiredLx(){
    const phid = mstform.getItem("user_htesfdysswy").getValue()
        let required = false
        if(phid == "01"){
          required = true
        }
        mstform.getItem("user_lxsqbh").setProps({
          required
        })
  }

    function parseUrlParams(url) {
        let result = {};

        // 先解析 # 之前的 query
        let [base, hash] = url.split('#');
        if (base.includes('?')) {
            let queryString = base.split('?')[1];
            Object.assign(result, parseQueryString(queryString));
        }

        // 再解析 # 之后的 query（如果有）
        if (hash && hash.includes('?')) {
            let queryString = hash.split('?')[1];
            Object.assign(result, parseQueryString(queryString));
        }

        return result;
    }

    function parseQueryString(queryString) {
        return queryString.split('&').reduce((params, param) => {
            if (!param) return params;
            let [key, ...values] = param.split('=');
            let value = values.join('=');
            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
            return params;
        }, {});
    }

    function getProjectInfoByPhid() {
        const phid = getHeadValue("user_lxsqbh")
        if (!phid) return
        $NG.execServer("getFblxInfoByChPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            const arr = [
                {
                    key: 'user_fbxmchsbh',
                    value: {
                        label:datas.chname,
                        value:datas.chphid
                    }
                },
                {
                    key:"PhidPc",
                    value:{
                        label:datas.phid_pc_exname,
                        value:datas.phid_pc
                    }
                },
                {
                    key: 'user_xmblb',
                    value: datas.xmblb
                },
                {
                    key: 'user_fbxmmc',
                    value: datas.fbxmmc,
                },
                {
                    key: 'user_fbxmlb',
                    value: {
                        value: datas.fbxmlb_phid,
                        label: datas.fbxmlb_name
                    },
                },{
                    key:"user_sfjyzhjssp",
                    value:{
                        label:datas.sfty_name,
                        value:datas.sfty_phid
                    }
                },
                {
                    key: 'user_jkjsfs',
                    value: datas.jkjsfs,
                },
                {
                    key: 'user_jkjsfs',
                    value: datas.jkjsfs,
                },
                {
                    key: 'user_yjfbzje',
                    value: datas.yjfbzje,
                },
                {
                    key: 'user_ncydzbfs',
                    value: {
                        label: datas.ncydzbfs_name,
                        value: datas.ncydzbfs_phid
                    }
                },
                {
                    key:'PhidCustomerEnt',
                    value:{
                        label:datas.u_fbfmc,
                        value:datas.u_fbfmc_name
                    }
                }
            ]
            setHeadValues(arr)

        })
    }

    // 获取分包商信息
    function getSupplyInfo() {
        const phid = mstform.getItem("PhidSupplyEnt").getValue()
        if (!phid) return
        $NG.execServer("getSupplyInfo", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            const arr = [
                {
                    key: "user_fbsxcfzr",
                    value: datas.user_fbsxcfzr
                },
                {
                    key: "user_fbsxcfzrsfzh",
                    value: datas.user_fbsxcfzrsfz
                },
                {
                    key: "user_fbsxcfzrlxdh",
                    value: datas.user_fbsxcfzrlxdh
                },
                {
                    key:"user_fbszzdj",
                    value:datas.user_zzdj
                },
                {
                    key:"user_sfwzxwqy",
                    value:datas.user_sfwzxwqy
                },
                {
                    key:"user_fddbr",
                    value:datas.person
                },
                {
                    key:"user_fddbrlxdh",
                    value:datas.user_fddbrlxdh
                },
                {
                    key:"user_fddbrsfzh",
                    value:datas.user_fddbrsfz
                },
                {
                    key:"user_nzbfbsdj",
                    value:{
                        label:datas.user_fbsdj_name,
                        value:datas.user_fbsdj
                    }
                },
                {
                    key:"user_hh",
                    value:datas.taxbank_id
                },{
                    key:"user_zh",
                    value:datas.accountno
                },{
                    key:"user_dh",
                    value:datas.taxtelephone,
                },
                {
                    key:"user_dz",
                    value:datas.taxaddress
                },{
                    key:"user_khh",
                    value:{
                        label:datas.phid_bank,
                        value:datas.bankname
                    }
                },
                {
                    key:"user_lxr",
                    value:datas.cname
                },
                {
                    key:"user_sj",
                    value:datas.handset
                },
                {
                    key:"user_fbszzdj",
                    value:datas.user_zzdj
                },
                {
                    key:"user_fbsdqyxz",
                    value:datas.user_fbsqyxz
                }
            ]
            setHeadValues(arr)
        })
    }

    // 隐藏系统表单的明细标签
    function hiddenDetail(detailKey) {
        const page = detailKey.reduce((value, item) => {
            value.push($NG.getCmpApi(item))
            return value
        }, [])
        // 开始隐藏
        page.forEach(docker => {
            if (docker) {
                const bigDom = docker.getRef().bodyRef.current
                //向上查找父元素是否存在，向上查找3级
                let temp_pNode = bigDom.parentNode
                let pNode = null
                for (let level = 0; level < 9; level++) {
                    if (temp_pNode && temp_pNode.className?.replaceAll(" ","") == 'udp-full-page') {
                        pNode = temp_pNode
                        break
                    }
                    temp_pNode = temp_pNode.parentNode
                    console.log(`temp`, temp_pNode , temp_pNode.className);
                }
                if (pNode) {
                    pNode.style.display = 'none'
                } else {
                    console.log(`没找到`, page);
                }
            }
        })
    }

    useValuesChange(()=>{
        sumCntDateDay()
    },"user_htjhkssj")

    useValuesChange(()=>{
        sumCntDateDay()
    },"user_htjhjssj")

    // 计算工期
    function sumCntDateDay(){
        const user_htjhkssj = mstform.getItem("user_htjhkssj").getValue()
        const user_htjhjssj = mstform.getItem("user_htjhjssj").getValue()
        calculateDateDifference(user_htjhkssj,user_htjhjssj)
        mstform.getItem("user_jhgq").setValue(calculateDateDifference(user_htjhkssj,user_htjhjssj))
    }
function calculateDateDifference(startDate, endDate) {
    // 将日期字符串转换为 Date 对象
    const start = new Date(startDate);
    const end = new Date(endDate);
    if(!startDate || !endDate) return 0

    // 获取两个日期的时间戳（毫秒）
    const timeDifference = end - start;

    // 计算天数，1天 = 24 * 60 * 60 * 1000 毫秒
    const daysDifference = timeDifference / (1000 * 3600 * 24);

    return Math.abs(daysDifference); // 返回绝对值，以防输入日期顺序不一致
}
    // 表头批量赋值
    function setHeadValues(arr) {
        arr.forEach(item => {
            console.log(`执行更新`,item);
            mstform.getItem(item.key)?.setValue(item.value)
        })
    }
})